// #define print(...)

class Solution {
public:
vector<string> generateParenthesis(int n) {
    vector<string> res;
    string ans;
    function<void(size_t,size_t)> bt = [&](size_t left, size_t right){
        if(ans.size() == n*2) res.push_back(ans);
        if(left < n){ // 左括号数少于总长度(2n)一半
            ans.push_back('(');
            bt(left+1, right);
            ans.pop_back();
        }
        if(right < left){ // 右括号数少于左括号
            ans.push_back(')');
            bt(left, right+1);
            ans.pop_back();
        }
    };
    bt(0,0);
    return res;
}
};
